package cn.com.qqgame.assistant;

import java.awt.Rectangle;
import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.sikuli.api.DesktopScreenRegion;
import org.sikuli.api.ScreenRegion;
import org.sikuli.api.robot.Mouse;
import org.sikuli.api.robot.desktop.DesktopMouse;

public class AssistantUtil {
	// Create a screen region object that corresponds to the default
	// monitor in full screen
	public static final ScreenRegion desktopScreenRegion = new DesktopScreenRegion();
	public static final Map<String, ScreenRegion> screenRegions = new HashMap<String, ScreenRegion>();

	public static final Mouse mouse = new DesktopMouse();

	static {
		try {
			final Field moveMouseDelayField = Class.forName(
					"org.sikuli.api.robot.desktop.AWTRobot").getDeclaredField(
					"MoveMouseDelay");
			moveMouseDelayField.setAccessible(true);
			moveMouseDelayField.set(null, new Float(0.1F)); // default is 0.5
															// second
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * List all images files under directory dir.
	 * 
	 * @param dir
	 *            Image directory.
	 * @return All images files under directory dir.
	 */
	public static File[] listImageFiles(final String dir) {
		final File[] imageFiles = new File(dir).listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				return pathname.getName().endsWith(".jpg");
			}
		});

		return imageFiles;
	}

	/**
	 * Get screen region which bounds is (x, y, width, height).
	 * 
	 * @param x
	 * @param y
	 * @param width
	 * @param height
	 * @return The screen region which bounds is (x, y, width, height).
	 */
	public static ScreenRegion getScreenRegion(final int x, final int y,
			final int width, final int height) {
		final String rectangle = String.format("%d_%d_%d_%d", x, y, width,
				height);
		ScreenRegion screenRegion = screenRegions.get(rectangle);
		if (screenRegion == null) {
			screenRegion = new DesktopScreenRegion();
			screenRegion.setBounds(new Rectangle(x, y, width, height));
			screenRegions.put(rectangle, screenRegion);
		}

		return screenRegion;
	}

	public static void sleep(final long millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			// Ignore
		}
	}
}
